package besta.moon.sql.expression.function.numeric;

import besta.moon.sql.expression.function.FunctionReturnInt;
import besta.moon.sql.expression.ExpressionArithmetic;
import besta.moon.sql.parser.SQLTokenizer;

public final class FunctionSign extends FunctionReturnInt {

    @Override
    public final int getFunction() {
        return SQLTokenizer.SIGN;
    }

    @Override
    public final int getInt() throws Exception {
        if (param1.isNull()) {
            return 0;
        }
        switch (ExpressionArithmetic.getBestNumberDataType(param1.getDataType())) {
            case SQLTokenizer.INT -> {
                int intValue = param1.getInt();
                if (intValue < 0) {
                    return -1;
                }
                if (intValue > 0) {
                    return 1;
                }
                return 0;
            }
            case SQLTokenizer.BIGINT -> {
                long longValue = param1.getLong();
                if (longValue < 0) {
                    return -1;
                }
                if (longValue > 0) {
                    return 1;
                }
                return 0;
            }
            case SQLTokenizer.MONEY -> {
                long longValue = param1.getMoney();
                if (longValue < 0) {
                    return -1;
                }
                if (longValue > 0) {
                    return 1;
                }
                return 0;
            }
            case SQLTokenizer.DECIMAL -> {
                return param1.getNumeric().getSignum();
            }
            case SQLTokenizer.DOUBLE -> {
                double doubleValue = param1.getDouble();
                if (doubleValue < 0) {
                    return -1;
                }
                if (doubleValue > 0) {
                    return 1;
                }
                return 0;
            }
            default -> throw new Error();
        }
    }
}
